package models;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;


import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.db.jpa.Blob;
import play.db.jpa.Model;

@Entity
public class Book extends Model {

	@Required
	@MaxSize(255)
	public String name;
	
	public Blob image;
	
	public String isbn;
	
	@Lob
	public String description;
	
	@OneToMany(mappedBy="book")
	public Set<BookCopy> copies = new HashSet<BookCopy>();
	
	@ManyToMany()
	@OrderBy("lastName") 
	public List<Author> authors = new ArrayList<Author>();
	
	@ManyToMany
	public Set<Tag> tags = new HashSet<Tag>();

	public Book() {
		super();
	}

	public Book(String name) {
		super();
		this.name = name;
	}
	
	@Override
	public String toString() {
		return name;
	}
	
	public Tag addTag(String name){
		Tag tag = Tag.find("byName", name).first();
		if (tag == null){
			tag = new Tag(name);
			tag.validateAndCreate();
		}
		tags.add(tag);
		return tag;
	}
	
	public Collection<Library> getLibraries(){
		TreeSet<Library> libraries = new TreeSet<Library>();
		for (BookCopy copy : copies){
			libraries.add(copy.library);
		}
		return libraries;
	}
	
	public boolean isAvilable(){
		for (BookCopy copy : copies){
			if( !copy.taken ){
				return true;
			}
		}
		return false;
	}
}

